<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/16
 * Time: 21:00
 */
namespace Pay\Controller;

use Common\Common\Api\Redis\Channel;
use Common\Common\Api\Redis\Product;
use Pay\Common\Api\Shouxin;

/**
 * Class ManyiController
 * @package Pay\Controller
 * 守信
 */
class ShouxinController extends PayController{
    protected $config;
	protected $class;
    public function __construct(){
        parent::__construct();
        $classes = explode("\\",__CLASS__);
        $class = end($classes);
        $this->class = substr($class, 0, stripos($class, "Controller"));
    }

    public function pay($array){
        $this->config = Channel::getInstance()->getById($array['channel']);

        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $product = Product::getInstance()->getById(I("request.pay_bankcode",0,"intval"));
        if(!$product){
            $this->showmessage('未找到支付产品!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );

        $return = $this->orderadd( $parameter );

        $data = [];

        $data['platformno'] = $this->config['mch_id'];

        $parameter = [];
        $parameter['payAmount'] = number_format($return['amount'],2,'.','');
        $parameter['commercialOrderNo'] = $return['orderid'];
        $parameter['callBackUrl'] = $return['notifyurl'];
        $parameter['notifyUrl'] = $return['callbackurl'];

        switch($this->config['paytype']) {
            //支付宝扫码
            case 3:
            case 4:
            $parameter['payType'] = '2';
                break;
            default:
                $this->showmessage('暂不支持此方式!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $json = json_encode($parameter);

        $data['parameter'] = Shouxin::encrypt($json, $this->config['signkey']);
        $data['sign'] = md5($json);
        $res = $this->_post($this->config['gateway'], $data);

        $res = json_decode($res,true);
        $code = $res['localtionView'];

        if($res['result'] !== 'success' || !$code){
            $this->showmessage('获取支付链接失败!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        echo $code;
    }

    private function _post($sRequestUrl, $aParams, $info = false) {
        //使用常规的表单POST方式提交
        $sPost = http_build_query($aParams);
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL, $sRequestUrl );
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $sPost);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
        curl_setopt($ch, CURLOPT_TIMEOUT, 20);

        $data = curl_exec($ch);
        $httpInfo = curl_getinfo($ch);
        curl_close($ch);

        if (isset($info) && $info) {
            return [$httpInfo, $data];
        } else {
            return $data;
        }
    }

    //通知
    public function notifyurl(){
        //$this->debug_callback();

        $p  = I("get.");
        /*$p = array (
            'platformno' => 'AC39520582',
            'callBackUrl' => 'http://callback.wanglianfu.com/Pay_Shouxin_notifyurl.html',
            'parameter' => 'cGH0E+Ctc74ZDOaKQMyTnpUHLYpP/bXlD6lsIDyOdCG1S8KDRBNP6DaIaXHVTcdj813trlbWUQf/ixD/ymBDJeMtIAITmgbjlF58E/bZyaF31RCtIgR5Ol5ATEc5C5IGSwxT24H0vXm2PDB/+K9PcSMVr6d+T79+1JlWergWqqg=',
            'sign' => '69ab09daf1071fb7de0c8fb68fcd6e8f',
            'merchantOrderNo' => '2019031716084566444',
        );*/

        if(empty($p)){
            exit("");
        }

        $this->config = M("Channel")->where(array('code'=>$this->class))->find();
        $json = Shouxin::decrypt($p['parameter'], $this->config['signkey']);
        $param = json_decode($json,true);
        if(empty($param)){
            echo 'param_decode_failed'; exit;
        }

        //获取订单信息
        $orderid = $param['commercialOrderNo'];
        $find = $this->checkOrderNotify($orderid);
        if(!$find){
            echo 'order_not_found'; exit;
        }

        //保存回调数据
        M("Order")->where(array("pay_orderid"=>$orderid))->save(array(

            "pay_orderid_rd"=>htmlspecialchars($p['platformno'])
        ));

        $sign = $p['sign'];
        $sign2 = md5($json);

        if($param['result'] !== 'success'){
            echo 'fail'; exit;
        }

        if($sign !== $sign2){
            echo 'sign_wrong';exit;
        }

        //回调成功
		$this->async($find['pay_orderid'],'success');
    }

    public function callBackUrl(){

        echo '操作成功'; exit;
    }
}